<template>
  <wd-form-item
    v-if="props.component.display === undefined || props.component.display === true"
    :component="props.component"
    :custom-field="props.customField"
  >
    <slot :name="`form-${props.component.dataIndex}`" v-bind="props.component">
      <el-input-number
        v-model="value"
        :size="props.component.size"
        :disabled="props.component.disabled"
        :readonly="props.component.readonly"
        :step="props.component.step ?? 1"
        :precision="props.component.precision ?? 0"
        :max="props.component.max ?? Infinity"
         :min="finalMin"
        :controls-position="props.component.position ?? 'right'"
      >
        <!-- 自定义减号按钮插槽 -->
        <template #decrease-icon v-if="props.component.decreaseIcon">
          <slot :name="`decreaseIcon-${props.component.dataIndex}`" />
        </template>
        <!-- 自定义加号按钮插槽 -->
        <template #increase-icon v-if="props.component.increaseIcon">
          <slot :name="`increaseIcon-${props.component.dataIndex}`" />
        </template>
      </el-input-number>
    </slot>
  </wd-form-item>
</template>

<script setup>
import { ref, inject, watch, computed } from "vue";
import { get, set, isNumber } from "lodash";

const props = defineProps({
  component: Object,
  customField: { type: String, default: undefined },
});

// 设置默认 min 为 1（如果没传入）
const finalMin = computed(() => {
  const min = props.component.min;
  return typeof min === 'number' ? (min > 0 ? min : 1) : 1;
});

// 获取 formModel（父级注入）
const formModel = inject("formModel");
const index = props.customField ?? props.component.dataIndex;
//info.work_years
// 初始化值（防止 undefined 闪烁）
const value = ref(get(formModel.value, index) ?? 0);

watch(
  () => get(formModel.value, index),
  (newVal) => {
    const num = Number(newVal);
    value.value = isNaN(num) ? 0 : num;
  }
);

watch(
  () => value.value,
  (val) => {
    const num = Number(val);
    set(formModel.value, index, isNaN(num) ? 0 : num);
  }
);
</script>
